package com.lqk.demo.Immutable;

import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lqk
 * @date 2022/1/5 10:34
 * <p>
 * SimpleDateFormat : 可变类 , 线程不安全
 *  解决:
 *      1. 使用 synchronized 关键字
 *          synchronized (sdf){
 *              try {
 *                  log.debug("{}", sdf.parse("1951-04-21"));
 *              } catch (Exception e) {
 *                  log.error("{}", e);
 *              }
 *          }
 *      2. 使用 ReentrantLock 加锁
 *          private static ReentrantLock lock = new ReentrantLock();
 *          ...
 *          lock.lock();
 *          try{
 *              try {
 *                  log.debug("{}", sdf.parse("1951-04-21"));
 *              } catch (Exception e) {
 *                  log.error("{}", e);
 *              }
 *          }finally {
 *              lock.unlock();
 *          }
 *      3. 使用不可变类, 保证线程安全
 */
@Slf4j
public class TestSimpleDateFormat {

    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                TemporalAccessor parse = dtf.parse("1951-04-21");
                log.debug("{}",parse);
            }).start();
        }
    }

    private static void test() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    log.debug("{}", sdf.parse("1951-04-21"));
                } catch (Exception e) {
                    log.error("{}", e);
                }
            }).start();
        }
    }
}
